package com.cw.lang.common.framework.feign.codec;

import java.lang.reflect.Type;

import com.cw.lang.common.constants.ControllerFlagConstant;
import com.cw.lang.common.enums.EnumBool;
import com.cw.lang.common.utils.context.ThreadContextStoreUtil;

import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.codec.Encoder;

/**
 * feign encoder包装类
 *
 * @author chenw
 * @version V2.1
 * @since 2.1.0 2019-03-23 10:35
 */
public class SpringEncoderWrapper implements Encoder {

    private Encoder encoder;

    public SpringEncoderWrapper(Encoder encoder) {
        this.encoder = encoder;
    }

    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
        ThreadContextStoreUtil.getInstance()
            .set(ControllerFlagConstant.FEIGN_CODEC_PROCESSING, EnumBool.YES);
        try {
            encoder.encode(object, bodyType, template);
        } finally {
            ThreadContextStoreUtil.getInstance()
                .removeKey(ControllerFlagConstant.FEIGN_CODEC_PROCESSING);
        }

    }
}
